﻿using UnityEngine;

public static class UnityExtension
{
    /// <summary>
    /// 递归查询子集
    /// </summary>
    /// <param name="go"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public static GameObject FindChild(this GameObject go, string name)
    {
        if (!go)
        {
            return null;
        }

        if (string.IsNullOrEmpty(name))
        {
            return null;
        }

        Transform transform = go.transform.Find(name);
        if( null != transform )
        {
            return transform.gameObject;
        }

        for (int i = 0; i < go.transform.childCount; ++i)
        {
            transform = go.transform.GetChild(i);
            if (null != transform)
            {
                var child = transform.gameObject.FindChild(name);
                if (null != child)
                {
                    return child;
                }
            }
        }
        return null;
    }

    public static T GetComponent<T>(this GameObject go, string name) where T : Component
    {
        if( !go ) 
        {
            return null;
        }

        if( name == go.name ) 
        {
            return go.GetComponent<T>();
        }

        var child= go.FindChild(name);
        if( null == child)
        {
            return null;
        }

        return child.GetComponent<T>();
    }

    public static T AddComponent<T>(this GameObject go, string name) where T : Component
    {
        if (!go)
        {
            return null;
        }

        if (name == go.name)
        {
            return go.AddComponent<T>();
        }

        var child = go.FindChild(name);
        if (null == child)
        {
            return null;
        }

        return child.AddComponent<T>();
    }

    public static T GetComponent<T>(this Transform tranform, string name) where T : Component
    {
        return tranform ? tranform.gameObject.GetComponent<T>(name) : null;
    }
}

